import urllib2
import json

def getData():

	url = "https://www.googleapis.com/mapsengine/v1/tables/16075412419356476951-12609446596071152052/features?version=published&key=AIzaSyCBCJgn8lEHekUbVZwq768lfpR0VZwrTl0"
	response = urllib2.urlopen(url)
	rawJson = response.read()
	jsonData = json.loads(rawJson)

	return jsonData

jsonData = getData()

def index():

	layerData = []

	for feature in jsonData["features"]:
		try:
			number = feature["properties"]["Property_N"]
		except:
			number = ""

		street = feature["properties"]["Street_Nam"]
		suburb = feature["properties"]["Redevelopm"]
		address = "%s %s, %s" % (number, street, suburb)

		lat = feature["properties"]["lat"]
		lng = feature["properties"]["lng"]

		fileNum = feature["properties"]["File_No_"]
		type = feature["properties"]["Type_of_De"]
		value = feature["properties"]["Estimated"]

		data = [fileNum, type, address, value, lat, lng]
		layerData.append(data)

	# this is a hack because the first bit of data in here is not right
	del layerData[0]

	return dict(layerData=layerData)


def goToFile():

	input = request.vars.docSearch
	docrequest = input.upper()

	layerData = []

	for feature in jsonData["features"]:

		if docrequest in feature["properties"]["File_No_"].upper():
			try:
				number = feature["properties"]["Property_N"]
			except:
				number = ""

			street = feature["properties"]["Street_Nam"]
			suburb = feature["properties"]["Redevelopm"]
			address = "%s %s, %s" % (number, street, suburb)

			lat = feature["properties"]["lat"]
			lng = feature["properties"]["lng"]

			fileNum = feature["properties"]["File_No_"]
			type = feature["properties"]["Type_of_De"]
			value = feature["properties"]["Estimated"]

			data = [fileNum, type, address, value, lat, lng]
			layerData.append(data)
		
		else:
			pass

	if len(layerData) == 0:
		layerData = "null"
	else:
		# hack to delete MRA-01308 as the geocded location is not right
		if layerData[0][0] == "MRA-01308":
			del layerData[0]
		else:
			pass

	return dict(layerData=layerData)